﻿using System;
using System.Collections;
using System.Reflection;

namespace DevelopAttributes {
    class Program {

        [Range (0, 30)]
        public static float mycount = -2;

        [Range (25.3f, 50.7f)]
        public static float myccounts = 28.0f;
        static void Main (string[] args) {
            Console.WriteLine ("Hello World!");

           // GetAttribute ();

            GetCustomAttribute();

            Console.WriteLine (mycount);
        }
        static void GetAttribute () {
            Program p = new Program ();
            FieldInfo _fieldInfo = typeof (Program).GetField ("mycount");

            FieldInfo[] fieldinfos = typeof (Program).GetFields ();

            foreach (var item in fieldinfos) {

            }
            //Console.WriteLine (_fieldInfo.Name);
            Range rangeAttribute = _fieldInfo.GetCustomAttribute (typeof (Range)) as Range;

            if (rangeAttribute.Min < (float) _fieldInfo.GetValue (typeof (Program)) && (float) _fieldInfo.GetValue (typeof (Program)) < rangeAttribute.Max) {
                Console.WriteLine ("当前合法");
            } else {
                Console.WriteLine ("当前不合法");
                var t1 = Math.Abs (rangeAttribute.Min - (float) _fieldInfo.GetValue (typeof (Program)));
                var t2 = Math.Abs (rangeAttribute.Max - (float) _fieldInfo.GetValue (typeof (Program)));
                float target = t1 > t2?rangeAttribute.Max : rangeAttribute.Min;
                _fieldInfo.SetValue (typeof (Program), target);
            }
        }
        static void GetCustomAttribute () {
            FieldInfo[] fieldinfos = typeof (Program).GetFields ();

            foreach (var item in fieldinfos) {
                Range _attribute=item.GetCustomAttribute(typeof(Range)) as Range;
                var value=item.GetValue(typeof(Program));
            }
        }
    }

    [AttributeUsage (AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
    public class Range : Attribute {
        private float max;
        private float min;
        public Range (float min, float max) {
            this.min = min;
            this.max = max;
        }
        public virtual float Max {
            get => max;
            set => max = value;
        }
        public virtual float Min {
            get => min;
            set => min = value;
        }
    }
}